<template>
	<view class="container">
    <view class="bg-img"><image src="http://wx.xiongmaovip.com/miniapp/static/chargeFuel/charging-bg.png"></image></view>
    <mvBar :mysNavConfig="mysNavConfig"></mvBar>
<!--		<view class="car_charge_info"-->
<!--			v-if="memberInfo.memberVo.member.carNo && memberInfo.memberVo.member.carBrand && memberInfo.memberVo.member.carRange"-->
<!--			@click="perfectCarInfo">-->
<!--			<text class="plate_num">{{memberInfo.memberVo.member.carNo}}</text>-->
<!--			<text class="year">{{memberInfo.memberVo.member.carBrand}}</text>-->
<!--			<text class="km">{{memberInfo.memberVo.member.carRange}}KM &nbsp;</text><uni-icons class="icon_right"-->
<!--				type="forward" color="#ffffff" size="15"></uni-icons>-->
<!--		</view>-->
<!--		<view class="car_charge_info" v-else @click="perfectCarInfo">-->
<!--			<text class="km">请完善车辆信息 &nbsp;</text><uni-icons class="icon_right" type="forward" color="#ffffff"-->
<!--				size="15"></uni-icons>-->
<!--		</view>-->
    <view class="charge_tips">
      <uni-icons type="info-filled" color="#C52813" size="20"></uni-icons> <text>充电时请不要在车内逗留，充电结束请尽快拔枪驶离</text>
    </view>
    <view class="nozExtInfo">
      <view class="A">
        <text>{{nozExtInfo.current}}A</text>
      </view>
      <view class="V">
        <text>{{nozExtInfo.voltageUpperLimits}}V</text>
      </view>
      <view class="KW">
        <text>{{nozExtInfo.power}}KW</text>
      </view>
    </view>
		<view class="charge_info_box">
      <view class="top-info">
        <view class="soc info-item">
          <view class="val">{{chrgeStatusInfo.soc}}%</view>
          <view class="titile">SOC</view>
        </view>
        <view class="endurance info-item">
          <view class="val">--KM</view>
          <view class="titile">续航</view>
        </view>
        <view class="residue info-item">
          <view class="val">--</view>
          <view class="titile">剩余</view>
        </view>
      </view>
      <view class="current-info">
        <view class="title">充电中<text>{{chrgeStatusInfo.soc}}%</text></view>
        <view class="sub">剩余充电时长：<text>--</text></view>
      </view>
			<view class="electricity_info">
				<view class="electricity">
					<view class="val">
						<text>{{Number(chrgeStatusInfo.totalPower).toFixed(2) || 0.00}}</text>
					</view>
					<view class="title">
						<text>充电量（度）</text>
					</view>
				</view>
				<view class="time">
					<view class="val">
						<text>{{hr}}:{{min}}</text>
					</view>
					<view class="title">
						<text>已充时间</text>
					</view>
				</view>
				<view class="amt">
					<view class="val">
						<text>￥{{Number(chrgeStatusInfo.totalMoney).toFixed(2) || 0.00}}</text>
					</view>
					<view class="title">
						<text>充电费用</text>
					</view>
				</view>
			</view>
      <view class="order_num">
        <text>订单编号：408970098</text>
      </view>
		</view>
<!--		<view class="stop_charge" @click="close()">-->
<!--			<text>停止</text>-->
<!--		</view>-->

    <view class="confirm-btn" @click="close">结束充电</view>
		<!-- 结束充电loading -->
		<uni-popup ref="lockPopup" background-color="none">
			<view class="unlock-popup-content">
				<view class="progress_content">
					<gb-progress :radius="100" :startPosDegree="0" :barWidth="10" originalColor="#999999"
						processColor="#ffffff" innerbgColor="#ffaa00" :process="process*10">
						<!-- <text class="second">{{process}}秒</text> -->
						<text class="second">结束中...</text>
					</gb-progress>
				</view>
				<view class="unlock_tips">
					<view>正在结束充电</view>
					<view>请耐心等待</view>
				</view>
			</view>
		</uni-popup>
		<loading ref="loading" :custom="true" :shadeClick="false" :type="1" @callback="callback()">
			<view class="test">
				<div class="spinnerContainer">
					<div class="spinner"></div>
					<div class="loader">
						<p>安全充电启动中，请勿拔枪</p>
					</div>
				</div>
			</view>
		</loading>
	</view>
</template>

<script>
	import {
		startCharge,
		chargeStatus,
		chargeStop,
		getGunOrStationInfo,
		completeChargeOrderDetails
	} from '@/api/index'
  import mvBar from "@/components/mysNavBar";
	import gbProgress from '@/uni_modules/gb-progress/components/gb-progress/gb-progress.vue'
	import loading from '@/components/xuan-loading.vue'
	export default {
		components: {
			gbProgress,
			loading,
      mvBar
		},
		data() {
			return {
				timer: null,
        mysNavConfig: {
          navPadding: true,
          isHome: false,
          navFixed: true,
          navTitle: {
            text: "充电中",
            color: "#FFFFFF",
            fontSize: "34upx", // px upx rpx
            fontWeight: "500", // blod
          },
          leftIconPath: '/static/header/back.png',
        },
				startChargeSeq: '',
				connectorId: '',
				timerType: 1, // 1-正常充电中的轮询 2-停止后的轮序
				stopCounts: 0, // 停止后的轮询次数
				chrgeStatusInfo: {},
				process: 1,
				hr: 0,
				min: 0,
				sec: 0,
				nozExtInfo: {
					connectorName: ''
				}, // 枪信息
				stationInfo: {}, // 站信息
				memberInfo: JSON.parse(uni.getStorageSync('memberInfo')), // 会员信息
				timer2: null,
				checkOrderCounts: 0, // 轮询订单状态次数
			}
		},
		// onReady() {
		// 	this.startChargeFn()
		// },
		onLoad(option, data) {
			console.log(option)
			// this.getChargeGunStationInfo()
			// this.countDateTime({startTime: '2023-12-28 23:50:50'})
			if (option.startChargeSeq && option.connectorId) {
				this.startChargeSeq = option.startChargeSeq
				this.connectorId = option.connectorId
				this.timerType = 1
				this.getChargeGunStationInfo()
				// toto 暂时不要
				// uni.showLoading({
				// 	title: '安全充电启动中，请勿拔枪'
				// });
				this.$refs.loading.open();
				this.checkChargeStatus(0)
			} else {
				console.log('参数异常')
			}
		},
		methods: {
			// 获取电枪+站点信息
			getChargeGunStationInfo() {
				console.log(this.connectorId, 'this.connectorIdthis.connectorId')
				getGunOrStationInfo({
					connectorId: this.connectorId, // 充电接口ID
				}).then(res => {
					console.log(res, 'getGunOrStationInfo')
					this.nozExtInfo = res.nozExt
					this.stationInfo = res.station
				}).catch(error => {
					console.log(error)
				})
			},
			// 时间计算
			countDateTime(data) {
				if (data && data.startTime) {
					const startDateStr = data.startTime.replace(/-/g, '/') //所有的- 都替换成/（IOS兼容处理）
					const curDate = new Date() // 当前时间
					const newStartDateStr = new Date(Date.parse(startDateStr))
					let newEndDateStr = curDate
					console.log(newStartDateStr.getTime())
					console.log(newEndDateStr.getTime())
					const micro_second = newEndDateStr.getTime() - newStartDateStr.getTime()
					// 总秒数
					const second = Math.floor(micro_second / 1000);
					// 天数
					const day = Math.floor(second / 3600 / 24);
					// 小时
					this.hr = Math.floor(second / 3600 % 24);
					// 分钟
					this.min = Math.floor(second / 60 % 60);
					// 秒
					this.sec = Math.floor(second % 60);
				}
			},
			// 查询订单状态
			chargeOrderDetails(time) {
				// uni.showLoading({
				// 	title: '支付中...'
				// });
				const self = this
				self.timer2 = setTimeout(() => {
					completeChargeOrderDetails({
						openid: uni.getStorageSync('userOpenId'), // 充电接口ID
						startChargeSeq: this.startChargeSeq, // 充电请求订单号
					}).then(res => {
						self.checkOrderCounts += 1
						console.log(res, 'orderStatus')
						if (res === 'creating' || res.paidStatus == 0) {
							if (self.checkOrderCounts >= 10) {
								clearTimeout(self.timer2)
								uni.showModal({
									title: '提示',
									content: '获取订单失败请联系管理员',
									showCancel: false,
									success: function(res) {
										if (res.confirm) {
											console.log('用户点击确定');
										} else if (res.cancel) {
											console.log('用户点击取消');
										}
									}
								})
							} else {
								self.chargeOrderDetails(5000)
							}
						} else {
							if (res.paidStatus === 1) {
								clearTimeout(self.timer2)
								// 已结束充电跳转至订单详情
								self.$refs.lockPopup.close()
								uni.reLaunch({
									url: '/pages/panda-charge/order-details/index?startChargeSeq=' +
										self.startChargeSeq
								})
							}
							clearTimeout(self.timer2)
						}
					}).catch(error => {
						console.log(error)
					})
				}, time)
			},
			// 查询充电状态
			checkChargeStatus(time) {
				const self = this
				self.timer = setTimeout(() => {
					chargeStatus({
						connectorId: this.connectorId, // 充电接口ID
						startChargeSeq: this.startChargeSeq, // 充电请求订单号
					}).then(res => {
						console.log(res, 'checkChargeStatus')
						self.countDateTime(res)
						const startChargeSeqStatus = res.startChargeSeqStatus
						self.chrgeStatusInfo = res
						// 如果这里返回的订单ID直接跳转到订单详情页面
						if (self.chrgeStatusInfo.chargeOrderId) {
							clearTimeout(self.timer)
							// 已结束充电跳转至订单详情
							self.chargeOrderDetails(0)
							// uni.reLaunch({
							// 	url:'/pages/panda-charge/order-details/index?startChargeSeq='+self.startChargeSeq
							// })
							return
						}
						// 这里面做状态判断是否继续查询
						if (startChargeSeqStatus >= 2) {
							// 关闭正在启动laoding
							// uni.hideLoading()
							this.$refs.loading.close();
						}
						if (startChargeSeqStatus == 5) {
							let _that = this
							uni.showModal({
								title: '提示',
								content: '启动失败，稍后自动退款',
								showCancel: false,
								success: function(res) {
									if (res.confirm) {
										console.log('用户点击确定');
										uni.navigateTo({
											url: '../charge-station-info/index?stationId=' +
												_that.stationInfo.stationId
										})
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							})
							return
						}
						if (self.timerType === 1) { // 充电中的轮询
							if (startChargeSeqStatus === 0 || startChargeSeqStatus === 1 ||
								startChargeSeqStatus === 2) {
								self.checkChargeStatus(5000)
							} else if (startChargeSeqStatus === 4) {
								clearTimeout(self.timer)
								// 已结束充电跳转至订单详情
								self.chargeOrderDetails(0)
								// self.$refs.lockPopup.close()
								// clearTimeout(self.timer)
								// uni.reLaunch({
								// 	url:'/pages/panda-charge/order-details/index?startChargeSeq='+self.startChargeSeq
								// })
							} else {
								clearTimeout(self.timer)
								console.log(res.startChargeSeqStatus, '0:初始 1：启动中2：充电中3：停止中4：已结束5：失败')
							}
						} else if (self.timerType === 2) { // 停止后的轮序
							self.stopCounts += 1
							self.process += 1
							if (startChargeSeqStatus === 4) {
								clearTimeout(self.timer)
								// 已结束充电跳转至订单详情
								this.chargeOrderDetails(0)
								// self.$refs.lockPopup.close()
								// clearTimeout(self.timer)
								// uni.reLaunch({
								// 	url:'/pages/panda-charge/order-details/index?startChargeSeq='+self.startChargeSeq
								// })
							} else if (startChargeSeqStatus !== 4 && self.stopCounts >= 7) {
								// 提示停止失败重新停止
								clearTimeout(self.timer)
								uni.showModal({
									title: '提示',
									content: '停止异常请重新停止',
									showCancel: false,
									success: function(res) {
										if (res.confirm) {
											console.log('用户点击确定');
										} else if (res.cancel) {
											console.log('用户点击取消');
										}
									}
								});
							} else {
								console.log(res.startChargeSeqStatus, '0:初始 1：启动中2：充电中3：停止中4：已结束5：失败')
								self.checkChargeStatus(5000)
							}
						}
					}).catch(error => {
						console.log(error)
						if (error == 500) {
							// 判断自动充满跳转页面 todo 不准确可能要调整
							clearTimeout(self.timer)
							uni.reLaunch({
								url: '/pages/panda-charge/order-details/index?startChargeSeq=' +
									self.startChargeSeq
							})
						} else {
							console.log(error)
						}
					})
				}, time)
			},
			// 结束充电loading
			toggle(type) {
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				this.$refs.lockPopup.open(type)
			},
			// 结束充电
			close() {
				this.toggle('center')
				chargeStop({
					connectorId: this.connectorId, // 充电接口ID
					startChargeSeq: this.startChargeSeq, // 充电请求订单号
				}).then(res => {
					console.log(res, 'checkChargeStatus')
					// todo结束之后再去做充电状态的查询,根据状态判断是否停止成功，停止成功后跳转到订单详情去支付
					this.timerType = 2
					this.stopCounts = 0
					this.checkChargeStatus(0)
				}).catch(error => {
					console.log(error)
				})
			},
			// 完善信息
			perfectCarInfo() {
				uni.navigateTo({
					url: '/pages/personal-center/personal-info/index'
				})
			}
		},
		destroyed() {
			// 离开页面销毁定时器
			clearTimeout(this.timer)
		}
	}
</script>

<style lang="scss">
	.container {
		text-align: center;

    .confirm-btn{
      position: fixed;
      left: 50%;
      bottom: 80upx;
      width: 700upx;
      line-height: 80upx;
      background: #006241;
      border-radius: 60upx;
      color: #FFFFFF;
      text-align: center;
      transform: translateX(-50%);
    }

    .bg-img{
      width: 100%;
      height: 670upx;
      position: absolute;
      top: 0;
      left: 0;
      z-index: -1;
      background: linear-gradient(180.13deg, #183E31 26.17%, rgba(30, 79, 62, 0.836286) 50.65%, rgba(39, 100, 79, 0.631583) 72.63%, rgba(63, 164, 130, 0) 99.89%);
      image{
        width: 100%;
        height: 100%;
      }
    }

		.car_charge_info {
			font-weight: 500;
			color: #FFFFFF;
			font-size: 28rpx;

			.year {
				display: inline-block;
				padding: 0 24rpx;
			}
		}

		.nozExtInfo {
			width: 100%;
			height: 520rpx;
			border-radius: 52rpx;
			font-weight: 400;
			color: #FFFFFF;
			font-size: 24rpx;
      padding: 80upx 32upx;
      box-sizing: border-box;
			.A,
			.V,
			.KW {
        width: 110upx;
        line-height: 56upx;
        background: #FFFFFF1A;
        border-radius: 40upx;
        margin-bottom: 18upx;
				flex: 1;
				text-align: center;
			}
		}

		.charge_ev_in {
			image {
				width: 100%;
				height: 444rpx;
			}
		}

		.charge_progress_info {
			display: flex;
			align-items: center;
			justify-content: center;

			.soc,
			.endurance,
			.residue {
				flex: 1;
				text-align: center;

				.titile {
					font-weight: 400;
					color: #FFFFFF;
					font-size: 26rpx;
				}

				.val {
					font-weight: 500;
					color: #FFFFFF;
					font-size: 32rpx;
				}
			}
		}

		.charge_info_box {
			width: 690rpx;
			padding: 32rpx 0 0;
			box-sizing: border-box;
      background: #FFFFFF;
			border-radius: 24rpx;
			margin: 0 auto;
      color: #1B1B1B;
      position: relative;

      .top-info{
        width: 100%;
        height: 230upx;
        background: linear-gradient(107.4deg, #64CAAB 35.39%, #1B8C6A 91.14%);
        position: absolute;
        top: -100upx;
        left: 0;
        border-radius: 24upx 24upx 0 0 ;
        z-index: -1;
        display: flex;
        justify-content: space-around;
        align-items: flex-start;
        .info-item{
          font-size: 24upx;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          line-height: 96upx;
          .val{
            margin-right: 16upx;
            font-size: 36upx;
            font-weight: 700;
          }
        }
      }

			.station_info {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.station_name {
					font-weight: 500;
					color: #1B1B1B;
					font-size: 28rpx;
				}
			}

			.order_num {
				//padding-top: 10rpx;
				//padding-bottom: 36rpx;
				text-align: left;
        margin-top: 36upx;
        border-top: 1px solid #F0F1F2;
        line-height: 84upx;
        padding: 0 24upx;

				text {
					display: inline-block;
					padding: 2rpx 8rpx;
					background: rgba(255, 255, 255, 0.08);
					border-radius: 4rpx;
					font-weight: 400;
					color: #6A6A6A;
					font-size: 28rpx;
				}
			}

      .current-info{
        text{
          color: #006241;
        }
        .title{
          font-size: 36upx;
          font-weight: 500;
          text{
            margin-left: 8upx;
            font-size: 64upx;
            font-weight: 700;
          }
        }
        .sub{
          color: #6A6A6A;
          font-size: 28upx;
          margin-top: 12upx;
        }
      }

			.electricity_info {
				display: flex;
				align-items: center;
				justify-content: center;
				padding-top: 24rpx;

				.electricity,
				.time,
				.amt {
					flex: 1;
					text-align: center;

					.val {
						font-weight: 500;
						color: #006241;
						font-size: 44rpx;
					}

					.title {
						padding-top: 8rpx;
						font-size: 26rpx;
						font-weight: 400;
						//color: rgba(255, 255, 255, 0.6);
					}
				}
			}
		}

		.charge_tips {
      width: 100%;
      //height: 72upx;
      background: #FEEBE8;
      line-height: 48upx;
      text-align: left;
      display: flex;
      align-items: center;

			text {
				padding: 0 14rpx;
				border-radius: 8rpx;
				//text-align: center;
				font-weight: 400;
				color: #C52813;
				font-size: 24rpx;
			}
		}

		.stop_charge {
			width: 278rpx;
			padding: 32rpx 100rpx;
			background: linear-gradient(180deg, #47C2FF 0%, #478BFF 100%);
			border-radius: 180rpx;
			text-align: center;
			margin: 120rpx auto auto auto;

			text {
				font-weight: 500;
				color: #FFFFFF;
				font-size: 40rpx;
			}
		}
	}

	.unlock-popup-content {
		width: 500rpx;
		padding: 20rpx;
		border-radius: 10rpx;
		background-color: #0ed4ee;

		.progress_content {
			display: flex;
			justify-content: center;

			.second {
				color: #ffffff;
				font-size: 28rpx;
				font-weight: bolder;
			}
		}

		.unlock_tips {
			padding-top: 10rpx;
			text-align: center;
			font-size: 30rpx;
			color: #ffffff;
		}

		.spinnerContainer {
			display: -webkit-box;
			display: -ms-flexbox;
			display: flex;
			-webkit-box-orient: vertical;
			-webkit-box-direction: normal;
			-ms-flex-direction: column;
			flex-direction: column;
			-webkit-box-align: center;
			-ms-flex-align: center;
			align-items: center;

			.spinner {
				width: 92rpx;
				height: 92rpx;
				display: grid;
				border: 4rpx solid #0000;
				border-radius: 50%;
				border-right-color: #ff6600;
				-webkit-animation: tri-spinner 1s infinite linear;
				animation: tri-spinner 1s infinite linear;
				margin-bottom: 20rpx;
			}

			.loader {
				color: #4a4a4a;
				font-weight: 500;
				font-size: 32rpx;
				-webkit-box-sizing: content-box;
				box-sizing: content-box;
				padding: 10rpx 10rpx;
				display: -webkit-box;
				display: -ms-flexbox;
				display: flex;
			}
		}

		.spinner::before,
		.spinner::after {
			content: "";
			grid-area: 1/1;
			margin: 4rpx;
			border: inherit;
			border-radius: 50%;
			-webkit-animation: tri-spinner 2s infinite;
			animation: tri-spinner 2s infinite;
		}

		.spinner::after {
			margin: 16rpx;
			-webkit-animation-duration: 3s;
			animation-duration: 3s;
		}

		@-webkit-keyframes tri-spinner {
			100% {
				-webkit-transform: rotate(1turn);
				transform: rotate(1turn);
			}
		}

		@keyframes tri-spinner {
			100% {
				-webkit-transform: rotate(1turn);
				transform: rotate(1turn);
			}
		}

		@-webkit-keyframes cycle-words {
			10% {
				-webkit-transform: translateY(-105%);
				transform: translateY(-105%);
			}

			25% {
				-webkit-transform: translateY(-100%);
				transform: translateY(-100%);
			}

			35% {
				-webkit-transform: translateY(-205%);
				transform: translateY(-205%);
			}

			50% {
				-webkit-transform: translateY(-200%);
				transform: translateY(-200%);
			}

			60% {
				-webkit-transform: translateY(-305%);
				transform: translateY(-305%);
			}

			75% {
				-webkit-transform: translateY(-300%);
				transform: translateY(-300%);
			}

			85% {
				-webkit-transform: translateY(-405%);
				transform: translateY(-405%);
			}

			100% {
				-webkit-transform: translateY(-400%);
				transform: translateY(-400%);
			}
		}

		@keyframes cycle-words {
			10% {
				-webkit-transform: translateY(-105%);
				transform: translateY(-105%);
			}

			25% {
				-webkit-transform: translateY(-100%);
				transform: translateY(-100%);
			}

			35% {
				-webkit-transform: translateY(-205%);
				transform: translateY(-205%);
			}

			50% {
				-webkit-transform: translateY(-200%);
				transform: translateY(-200%);
			}

			60% {
				-webkit-transform: translateY(-305%);
				transform: translateY(-305%);
			}

			75% {
				-webkit-transform: translateY(-300%);
				transform: translateY(-300%);
			}

			85% {
				-webkit-transform: translateY(-405%);
				transform: translateY(-405%);
			}

			100% {
				-webkit-transform: translateY(-400%);
				transform: translateY(-400%);
			}
		}
	}
</style>